// Set new default font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = 'Nunito, -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';

let myForecastingChart;  // 用于存储 Chart 实例
const dataTableSelect = document.getElementById('dataTableSelect');

// 初始化时加载图表
window.onload = function() {
    fetchDataAndCreateChart(dataTableSelect.value);  // 使用默认值初始化请求
};

// 监听下拉框值的变化
dataTableSelect.addEventListener('change', function () {
    fetchDataAndCreateChart(this.value);  // 使用当前值请求数据
});

// 创建图表或更新图表
function fetchDataAndCreateChart(transactionType) {
    axios.get("http://localhost:8080/transactions/selectAmounts", {
        params: {
            "userId": localStorage.getItem("userId"),
            "transactionType": transactionType  // 使用选择的值
        }
    }).then(response => {
        const amounts = response.data.data;
        const keys = Object.keys(amounts);
        const values = keys.map(key => amounts[key]);

        // 如果图表实例已存在，则更新数据; 否则创建新图表
        if (myForecastingChart) {
            myForecastingChart.data.labels = keys;  // 更新 x 轴标签
            myForecastingChart.data.datasets[0].data = values;  // 更新数据点
            myForecastingChart.update();  // 更新图表
        } else {
            // 创建新的 Chart 实例
            const ctx = document.getElementById("myForecastingChart").getContext('2d');
            myForecastingChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: keys,
                    datasets: [{
                        label: 'Amounts Forecasting',
                        data: values,
                        borderColor: '#4e73df',
                        backgroundColor: 'rgba(78, 115, 223, 0.2)',
                        borderWidth: 2,
                        pointRadius: 5,
                        pointBackgroundColor: '#4e73df',
                        pointBorderColor: '#ffffff',
                        pointHoverRadius: 7,
                        hoverBackgroundColor: '#ffffff',
                        hoverBorderColor: "#7c7c7c",
                        fill: true,
                        hitRadius: 10
                    }],
                },
                options: {
                    maintainAspectRatio: false,
                    tooltips: {
                        backgroundColor: "rgb(255,255,255)",
                        bodyFontColor: "#858796",
                        borderColor: '#dddfeb',
                        borderWidth: 1,
                        xPadding: 15,
                        yPadding: 15,
                        displayColors: false,
                        caretPadding: 10,
                        callbacks: {
                            label: function (tooltipItem, data) {
                                var label = data.datasets[tooltipItem.datasetIndex].label || '';
                                if (label) {
                                    label += ': ';
                                }
                                label += tooltipItem.yLabel; // 使用 y 轴的值
                                return label;
                            }
                        }
                    },
                    legend: {
                        display: true,
                        position: 'top',
                    },
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true,
                                suggestedMax: 60,
                            },
                            scaleLabel: {
                                display: true,
                                labelString: 'Values'
                            }
                        }],
                        xAxes: [{
                            scaleLabel: {
                                display: true,
                                labelString: 'Categories'
                            }
                        }]
                    },
                },
            });
        }
    }).catch(error => {
        console.error("Error fetching data: ", error);
    });
}